/*
 * @Author: wangtao
 * @Date: 2020-10-21 18:43:09
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-05-31 09:47:37
 * @Description: file content
 */
import React, { Component, Fragment } from 'react';
import {
  StyleSheet,
  View, Text,
  NativeModules,
  TouchableOpacity,
  Keyboard,
  Image
} from 'react-native';
import {
  px2dp,
  isAndroid,
  mainBgColorWhite,
  screenHeight,
  screenWidth,
  fontColorCoffee,
  mainBgColorLightGray,
  splitLineColorLightGray,
  fontColorBlack,
  fontColorSecDeepGray
} from '@/styles';
import { msg, Button, _ } from '@/common';
import supply from '@/api/supply';
import { debounce } from '@/common/util';
import DateTimePicker from 'react-native-modal-datetime-picker';
import Moment from 'moment';
import { iconRightGray } from '@/images';
import AddTruckBox from './components/add-truck-box';
import FeedBackDriverCer from '../truck-cert/components/driver-cer-feedback';
import SearchLegal from './components/search-legal';
import SimpleRowItem from '../../../components/SimpleRowItem';
import SelectItem from './components/select-item';
import InputItem from './components/input-item';

const { Submit } = Button;
/**
 * @modifyAuthor kanglang
 * @description 新增车辆页面
 * @createDate 2020/8/27
 */

export default class AddTruck extends Component {
  constructor(props) {
    super(props);
    const { customRouters } = props;
    this.state = {
      state: null, // 预约状态：  0.预约不存在 进行预约流程   1.预约已存在 等待平台创建合同（等待页面）   2.预约处理中  合同已创建(各种签署状态的流程)     3.合同已完成
      signState: null, // 签署状态： state=2  才会有 签署状态的判断
      instId: null, // 合同实例id
      contractUrl: null, // 合同实例文件
      message: null, // 视频拒绝理由
      nextGo: null, // 签署状态参与判断时  下一步应该做什么
      productName: null, // 产品名
      mobile: null, // 验证用的手机号
      legalList: [],
      searchValue: '',
      status: customRouters && customRouters.status || 0,
      currentLegal: {},
      coopType: null,
      projectCode: null,
      symodel: ['1'],
      capitalPersent: '', // 出资比例
      capitalAmount: '', // 认缴金额
      projectList: [], // 签约的项目列表
      invalidTimeStartStr: '',
      invalidTimeEndStr: '',
      tgTimeStartStr: '',
      tgTimeEndStr: '',
      zlTimeStartStr: '',
      isTimeShow: false,
      isTimeType: '',
      projectName: '',
      keyboardHeight: 0
    };
  }

  static getDerivedStateFromProps(nextProps, preState) {
    const status = (nextProps.customRouters && nextProps.customRouters.status) || 0;
    const coopType = (nextProps.customRouters && nextProps.customRouters.coopType) || null;
    return { status, coopType };
  }

  componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', event => {
      this._keyboardDidShow(event);
    });
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', event => {
      this._keyboardDidHide(event);
    });
    const { onChangeAddTruck } = this.props;
    onChangeAddTruck && onChangeAddTruck({ status: 0, coopType: null });
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  _keyboardDidShow = (e) => {
    this.setState({
      keyboardHeight: e.endCoordinates.height,
    });
  }

  _keyboardDidHide = (e) => {
    this.setState({
      keyboardHeight: 0,
    });
  }

  render() {
    const { status, searchValue, legalList, coopType,
      symodel, capitalPersent, capitalAmount, projectList,
      isTimeShow, invalidTimeStartStr, invalidTimeEndStr,
      tgTimeStartStr, tgTimeEndStr, zlTimeStartStr, keyboardHeight
    } = this.state;
    const syList = [
      {
        name: '定额收益',
        value: '1'
      },
      {
        name: '绩效收益',
        value: '2'
      }
    ];
    return (
      <View style={[styles.safeContainer, !isAndroid && { minHeight: screenHeight - px2dp(300) }]}>
        {
          status == 0 ?
            <View>
              <Text style={styles.searchTip}>请选择您要入驻的物流公司</Text>
              <SearchLegal
                searchValue={searchValue}
                changeAddress={this.changeAddress}
                clear={this.clear}
              />
              {
                legalList.length > 0 && legalList.map((item, index) => {
                  return (
                    <TouchableOpacity style={styles.compylist} onPress={() => this.selectLegal(item)}>
                      <Text>{item.entName}</Text>
                      <Image source={iconRightGray} style={styles.rightIcon} />
                    </TouchableOpacity>
                  );
                })
              }
            </View> :
            status == 1 ?
              <>
                <View style={styles.ddContainer}>
                  <Text style={styles.truckTip}>你要签约的车辆类型是？</Text>
                </View>
                <View>
                  {
                    projectList.length > 0 && projectList.map((item, index) => {
                      return (
                        <View style={styles.partOne}>
                          <AddTruckBox
                            truckIcon={{ uri: item.picUrl }}
                            certType={item.projectName}
                            titleOne={item.remark}
                            titleTwo={item.chareType}
                            onHandleCert={() => this.selectJMType(item)}
                          />
                        </View>
                      );
                    })
                  }
                </View>
              </> :
              <View style={styles.finishBox}>
                <Text style={styles.finishTip}>请完善合同条款</Text>
                {
                  coopType == 1 ?
                    <View>
                      <View>
                        <Text>车辆加盟起止日期</Text>
                        <View
                          style={styles.itemBox}
                        >
                          <TouchableOpacity
                            style={[styles.startAndEndTimeWrap]}
                            onPress={() => {
                              this.setState({
                                isTimeShow: true,
                                isTimeType: 'invalidTimeStartStr',
                              });
                            }}
                            activeOpacity={0.8}
                          >
                            <Text style={{ color: invalidTimeStartStr ? fontColorBlack : fontColorSecDeepGray }}>{invalidTimeStartStr || '必填，起始日期'}</Text>
                          </TouchableOpacity>
                          <View style={styles.timeLine} />
                          <TouchableOpacity
                            style={[styles.startAndEndTimeWrap]}
                            onPress={() => {
                              this.setState({
                                isTimeShow: true,
                                isTimeType: 'invalidTimeEndStr',
                              });
                            }}
                            activeOpacity={0.8}
                          >
                            <Text style={{ color: invalidTimeEndStr ? fontColorBlack : fontColorSecDeepGray }}>{invalidTimeEndStr || '必填，截止日期'}</Text>
                          </TouchableOpacity>
                        </View>
                      </View>
                    </View> :
                    coopType == 2 ?
                      <View style={{ marginBottom: Number(keyboardHeight) }}>
                        <View>
                          <Text>车辆托管起止日期</Text>
                          <View
                            style={styles.itemBox}
                          >
                            <TouchableOpacity
                              style={[styles.startAndEndTimeWrap]}
                              onPress={() => {
                                this.setState({
                                  isTimeShow: true,
                                  isTimeType: 'tgTimeStartStr',
                                });
                              }}
                              activeOpacity={0.8}
                            >
                              <Text style={{ color: tgTimeStartStr ? fontColorBlack : fontColorSecDeepGray }}>{ tgTimeStartStr || '必填，起始日期'}</Text>
                            </TouchableOpacity>
                            <View style={styles.timeLine} />
                            <TouchableOpacity
                              style={[styles.startAndEndTimeWrap]}
                              onPress={() => {
                                this.setState({
                                  isTimeShow: true,
                                  isTimeType: 'tgTimeEndStr',
                                });
                              }}
                              activeOpacity={0.8}
                            >
                              <Text style={{ color: tgTimeEndStr ? fontColorBlack : fontColorSecDeepGray }}>{tgTimeEndStr || '必填，截止日期'}</Text>
                            </TouchableOpacity>
                          </View>
                        </View>
                        <View style={styles.itemMar}>
                          <Text>收益模式</Text>
                          <View style={{ flexDirection: 'row', marginTop: px2dp(24) }}>
                            {
                              syList.map((item) => {
                                return (
                                  <SelectItem
                                    name={item.name}
                                    type='symodel'
                                    value={item.value}
                                    activeVal={symodel}
                                    onChange={(type, value) =>
                                      this.onChange(type, value)}
                                  />
                                );
                              })
                            }
                          </View>

                        </View>
                        <View style={styles.itemMar}>
                          <Text>车辆出资份额占比</Text>
                          <InputItem
                            name='capitalPersent'
                            value={capitalPersent}
                            placeholder='必填，请输入车辆出资份额占比'
                            unit='%'
                            onChangeValue={this.onChangeAmount}
                          />
                        </View>
                        <View style={styles.itemMar}>
                          <Text>认缴金额</Text>
                          <InputItem
                            name='capitalAmount'
                            value={capitalAmount}
                            placeholder='必填，请输入认缴金额'
                            unit='元'
                            onChangeValue={this.onChangeAmount}
                          />
                        </View>
                      </View> :
                      <View>
                        <View>
                          <Text>车辆租赁开始日期</Text>
                          <View
                            style={styles.itemBox}
                          >
                            <TouchableOpacity
                              style={[styles.startAndEndTimeWrapTwo]}
                              onPress={() => {
                                this.setState({
                                  isTimeShow: true,
                                  isTimeType: 'zlTimeStartStr',
                                });
                              }}
                              activeOpacity={0.8}
                            >
                              <Text style={{ alignItems: 'flex-start' }}>{zlTimeStartStr || '必填，起始日期'}</Text>
                            </TouchableOpacity>
                          </View>
                        </View>
                      </View>
                }
              </View>
        }
        {
          (coopType != null) &&
          <View style={[styles.btnBox, !isAndroid && { marginBottom: px2dp(160) }]}>
            <Submit
              text='生成合同'
              onClick={() => {
                this.onHandleCert();
              }}
              boxStyle={styles.boxStyle}
              btnTextStyle={{
                fontSize: px2dp(32),
              }}
            />
          </View>
        }
        <DateTimePicker
          isVisible={isTimeShow}
          mode='date'
          cancelTextIOS='取消'
          confirmTextIOS='确认'
          headerTextIOS='选取日期'
          locale='zh_CN'
          onConfirm={(val) => {
            this.handleConfirm(val);
          }}
          onCancel={() => {
            this.handleCancel();
          }}
        />
      </View>
    );
  }

  // 输入回调
  changeAddress = (val) => {
    if (Number(val) <= 0) {
      return;
    }
    this.setState({ searchValue: val }, () => {
      debounce(() => this.findLegal(), 300);
    });
  }

  // 清空
  clear = () => {
    this.setState({ searchValue: '', legalList: [] });
  }

  // 选择物流公司
  selectLegal = (legal) => {
    const { onChangeAddTruck } = this.props;
    this.setState({ status: 1, currentLegal: legal }, () => {
      supply.findProjectByLegal({ legalCustId: legal.enterpriseId }).then(res => {
        if (res.success) {
          onChangeAddTruck && onChangeAddTruck({ status: 1, coopType: null });
          this.setState({ projectList: res.data }, () => {
            this.clear();
          });
        } else {
          this.setState({ status: 0, projectList: [] });
        }
      });
    });
  }

  findLegal = () => {
    const { searchValue } = this.state;
    supply.getLegal({ entName: searchValue }).then(res => {
      if (res.success) {
        this.setState({ legalList: res.data });
      } else {
        this.setState({ legalList: [] });
      }
    });
  }

  // 选择加盟类型
  selectJMType = (item) => {
    const { onChangeAddTruck } = this.props;
    this.setState({
      coopType: item.coopType,
      projectCode: item.projectCode,
      projectName: item.projectName,
      status: 2
    }, () => {
      this.clear();
      onChangeAddTruck && onChangeAddTruck({ status: 2, coopType: item.coopType });
    });
  }

  // 选择收益模式
  onChange = (type, value) => {
    this.setState({ [type]: value });
  }

  // 输入出资比例和认缴金额
  onChangeAmount = (name, text) => {
    if (name != 'capitalAmount') {
      if (Number(text) <= 0) {
        this.setState({ [name]: '' });
        return;
      }
      if (Number(text) > 100) {
        this.setState({ [name]: '100' });
        return;
      }
    }
    // 清理非数字.
    text = _.clearNoNum(text);
    // 保留两位小数
    text = _.clearDotNumTo2(text);
    this.setState({ [name]: text });
  }

  handleConfirm = (val) => {
    const { isTimeType } = this.state;
    this.setState({ [isTimeType]: Moment(val).format('YYYY/MM/DD') });
    this.setState({ isTimeShow: false });
  };

  handleCancel = (val) => {
    this.setState({ isTimeShow: false });
  };

  //  发起签约
  onHandleCert = () => {
    const { data } = this.props;
    const { capitalAmount, invalidTimeStartStr, invalidTimeEndStr, currentLegal,
      capitalPersent, symodel, coopType, projectCode, projectName,
      tgTimeStartStr, tgTimeEndStr, zlTimeStartStr
    } = this.state;
    let startTime = '';
    let endTime = '';
    if (coopType == 1) {
      if (!invalidTimeStartStr || !invalidTimeEndStr) {
        return msg.emit('app:tip', { text: '请选择车辆加盟起止日期' });
      }
      startTime = invalidTimeStartStr;
      endTime = invalidTimeEndStr;
    } else if (coopType == 2) {
      if (!tgTimeStartStr || !tgTimeEndStr) {
        return msg.emit('app:tip', { text: '请选择车辆托管起止日期' });
      } if (!capitalPersent) {
        return msg.emit('app:tip', { text: '请输入车辆出资份额占比' });
      } if (!capitalAmount) {
        return msg.emit('app:tip', { text: '请输入认缴份额' });
      }
      startTime = tgTimeStartStr;
      endTime = tgTimeEndStr;
    } else if (coopType == 3) {
      if (!zlTimeStartStr) {
        return msg.emit('app:tip', { text: '请选择车辆租赁开始日期' });
      }
      startTime = zlTimeStartStr;
    }
    console.log(startTime);
    console.log(endTime);
    console.log(data);

    NativeModules.WindowModule.showWindow(
      {
        title: `确定签约${projectName}`,
        content: '注：选择后不能更换',
      },
      (e) => {
        if (e == 1) {
          msg.emit('router: goToNext', {
            routeName: 'ContractDetail',
            contractStatus: 1,
            routerFrom: 'AddTruck',
            data: {
              amount: capitalAmount, // 缴纳金额 托管车
              startTime: startTime, // 对标的车的共建期限起 托管车
              endTime: endTime, // 对标的车的共建期限止 托管车
              legalCustId: currentLegal && currentLegal.enterpriseId, // 法人id
              percent: capitalPersent, // 车辆进行出资共建, 占标的车辆 __% 的营运收 托管车
              personCheck: Number(symodel[0]), // 1定额收益; 2绩效收益
              projectCode: projectCode, // 项目code
              type: coopType, // 1加盟车 2托管车  3运力租赁
              ...data
            }
          });
        }
      },
    );
  };

  //  跳转去认证(用户中断操作，跳转不同页面)
  goToCert = () => {
    const { contractUrl, instId, signState, productName, mobile, message } = this.state;
    storage.save({
      key: 'contractId', // 注意:请不要在key中使用_下划线符号!
      data: instId
    });

    if (signState === 0) {
      msg.emit('router: goToNext', {
        routeName: 'previewContract',
        pdfUrl: contractUrl,
        contractState: true,
        instId
      });
    }
    if (signState === 1) {
      msg.emit('router: goToNext', {
        routeName: 'videoCapture',
      });
    }

    if (signState === 2) {
      return <FeedBackDriverCer
        status={1}
        title={`您已选择签约${productName}`}
        desc='等待平台审核视频'
      />;
    }
    if (signState === 3) {
      return <FeedBackDriverCer
        status={0}
        title='非常抱歉，您未通过视频认证'
        desc={`原因:${message}`}
        onChange={() => {
          msg.emit('router: goToNext', {
            routeName: 'videoCapture',
          });
        }}
      />;
    }
    // 去发短信验证
    if (signState === 4) {
      msg.emit('router: goToNext', {
        routeName: 'contractConfirmation',
        mobile
      });
    }
    // 去签名
    if (signState === 5) {
      msg.emit('router: goToNext', {
        routeName: 'autograph',
      });
    }
    if (signState === 6) {
      return <FeedBackDriverCer
        status={1}
        title={`您已选择签约${productName}`}
        desc='等待平台授权'
      />;
    }
  };
}
const styles = StyleSheet.create({
  safeContainer: {
    width: screenWidth,
    minHeight: screenHeight - px2dp(240),
    paddingBottom: px2dp(32),
    backgroundColor: mainBgColorWhite
  },
  compylist: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    borderBottomColor: '#eee',
    borderBottomWidth: px2dp(1),
    marginHorizontal: px2dp(40),
    paddingBottom: px2dp(20),
    paddingTop: px2dp(20)
  },
  rightIcon: {
    marginLeft: px2dp(8) * 2,
    height: px2dp(32),
    width: px2dp(32)
  },
  searchTip: {
    color: '#343332',
    fontSize: px2dp(40),
    marginLeft: px2dp(32),
    paddingTop: px2dp(50),
    paddingBottom: px2dp(32)
  },
  ddContainer: {
    backgroundColor: '#FFFFFF',
    paddingTop: px2dp(36) * 2,
    paddingBottom: px2dp(28) * 2,
    paddingLeft: px2dp(24) * 2,
    borderBottomLeftRadius: px2dp(12) * 2,
    borderBottomRightRadius: px2dp(12) * 2,
  },
  truckTip: {
    color: '#343332',
    fontSize: px2dp(24) * 2,
  },
  partOne: {
    height: px2dp(155) * 2,
    marginTop: px2dp(50) * 2,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },

  partTwo: {
    height: px2dp(155) * 2,
    marginTop: px2dp(80) * 2,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  finishBox: {
    padding: px2dp(32)
  },
  finishTip: {
    fontSize: px2dp(40),
    color: '#343332',
    paddingVertical: px2dp(48),
    textAlign: 'left'
  },
  btnBox: {
    flex: 1,
    width: '100%',
    // position: 'absolute',
    marginBottom: px2dp(80),
    justifyContent: 'center',
    alignItems: 'center',
  },
  amountSelect: {
    marginTop: px2dp(24),
    paddingHorizontal: px2dp(24),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
  },
  goodsWrapPriceTextInput: {
    fontSize: px2dp(28),
    height: px2dp(88),
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    paddingTop: 0,
    paddingBottom: 0,
  },
  itemMar: {
    marginTop: px2dp(48)
  },
  startAndEndTimeWrap: {
    fontSize: px2dp(28),
    height: px2dp(72),
    width: '42%',
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: px2dp(4),
  },
  startAndEndTimeWrapTwo: {
    fontSize: px2dp(28),
    height: px2dp(72),
    width: '100%',
    backgroundColor: mainBgColorLightGray,
    alignItems: 'flex-start',
    justifyContent: 'center',
    borderRadius: px2dp(4),
    paddingLeft: px2dp(24)
  },
  timeLine: {
    width: px2dp(32),
    height: 1,
    backgroundColor: splitLineColorLightGray,
    marginHorizontal: px2dp(30),
  },
  boxStyle: {
    width: screenWidth - px2dp(110),
    height: px2dp(96),
    borderWidth: 1,
    borderColor: fontColorCoffee,
    borderRadius: px2dp(8),
  },
  itemBox: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: px2dp(24),
    // flex:1,
  }
});
